import React from 'react';
import classNames from 'classnames';

import * as Sys from '../../sys';
import * as SysBom from '../../sys.bom';
import * as BooksApi from './books.api';
import { DetailButton } from '../../components/buttons';
import { ISubmitEvent } from 'src/sys.dom';

interface IBookListProps {
    books: BooksApi.Book[]
}

export class BookList extends React.Component<IBookListProps> {
    constructor(props: IBookListProps) {
        super(props);
    }

    static defaultProps: IBookListProps = {
        books: [],
    };

    private detail = (evt: React.MouseEvent<HTMLButtonElement>) => {
        const bookId = evt.currentTarget.getAttribute('data-key');
        SysBom.jumpTo('detail?book-id=' + bookId);
    };

    render = (): JSX.Element => {
        const rows: JSX.Element[] = this.props.books.map(item => <tr key={'r_' + item.bookId}
            className={classNames({ 'warning': item.amount === 0 })}>
            <th scope="row" className="right aligned">
                {item.bookId}
            </th>
            <td className="center aligned">
                {BooksApi.formatBookCategory(item.category)}
            </td>
            <td className="center aligned">
                {item.title}
            </td>
            <td className="center aligned">
                {item.author}
            </td>
            <td className="center aligned">
                {Sys.formatDate(item.pubDate)}
            </td>
            <td className="right aligned">
                {Sys.formatNumber(item.price)}
            </td>
            <td className="right aligned">
                {Sys.formatNumber(item.amount, 0)}
            </td>
            <td className="center aligned">
                {item.star && <i className="large green star icon" />}
            </td>
            <td className="center aligned">
                <DetailButton data-key={item.bookId} onClick={this.detail} />
            </td>
        </tr>);

        return <table className="ui unstackable selectable striped table">
            <thead>
                <tr>
                    <th scope="col" className="right aligned">Id</th>
                    <th scope="col" className="center aligned">Category</th>
                    <th scope="col" className="center aligned">Title</th>
                    <th scope="col" className="center aligned">Author</th>
                    <th scope="col" className="center aligned">Pub date</th>
                    <th scope="col" className="right aligned">Price</th>
                    <th scope="col" className="right aligned">Amount</th>
                    <th scope="col" className="center aligned">Star</th>
                    <th scope="col" className="center aligned" />
                </tr>
            </thead>
            <tbody>
                {rows}
            </tbody>
        </table>;
    }
}